package org.example.servlet;

import org.example.dao.UserDao;
import org.example.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户登录Servlet
 */
public class LoginServlet extends HttpServlet {
    
    private UserDao userDao;
    
    @Override
    public void init() throws ServletException {
        userDao = new UserDao();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");
        
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        
        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            out.println("<script>alert('验证码错误'); history.back();</script>");
            return;
        }
        
        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            out.println("<script>alert('用户名不能为空'); history.back();</script>");
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            out.println("<script>alert('密码不能为空'); history.back();</script>");
            return;
        }
        
        // 验证用户
        UserDao.User user = userDao.findByUsername(username);
        if (user == null || !PasswordUtil.checkPassword(password, user.getPassword())) {
            out.println("<script>alert('用户名或密码错误'); history.back();</script>");
            return;
        }
        
        // 登录成功，保存用户信息到session
        session.setAttribute("user", user);
        session.removeAttribute("captcha"); // 清除验证码
        
        out.println("<script>alert('登录成功'); window.location.href='index.html';</script>");
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 处理退出登录
        String action = request.getParameter("action");
        if ("logout".equals(action)) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            response.sendRedirect("login.html");
        }
    }
}
